import React, {useEffect, useState} from 'react'
import {Form, Button, Modal, Row, Col, Upload, Spin, notification} from 'antd'
import {connect} from 'umi'
import EditDegradeTable from './EditDegradeTable'
import SelectUserModal from "@/pages/components/SelectUserModal"
import {getSecurityEmployeeInfo} from '../../service'
import {importEmployeeSecurity} from '@/pages/Security/service'
import {PlusOutlined, UploadOutlined, DownloadOutlined} from '@ant-design/icons'
import {socialSecurityTemplateURL} from "@/utils/constant";

const FormItem = Form.Item;
const formLayout = {
  labelCol: {span: 7},
};

const CreateForm = (props) => {
  const {onCancel, visible, current, type} = props;
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [loadingText, setLoadingText] = useState('');
  const [userModalVisible, setUserModalVisible] = useState(false);
  const [securityInfo, setSecurityInfo] = useState({});
  const [addUserList, setAddUserList] = useState([]);
  const [securityUserItems, setSecurityUserItems] = useState([]);
  const [renderFlag, setRenderFlag] = useState(false);

  useEffect(() => {
    if (current && visible) {
      let {securityId} = current;
      setSecurityInfo({type: type, typeId: securityId});
      setLoadingText('人员数据加载中...');
      setLoading(true);
      getSecurityEmployeeInfo(current.securityId).then(res => {
        let securityUserList = [...res];
        if (res.length > 0) {
          setSecurityUserItems(securityUserList);
          current.securityUsers = securityUserList;
          form.setFieldsValue(current);
        } else {
          current.securityUsers = [];
          form.setFieldsValue(current);
        }
        setLoading(false);
      })
    }
  }, [visible, renderFlag]);

  const fileProps = {
    name: 'file',
    multiple: false,
    showUploadList: false,
    customRequest: (info)=> {
      setLoadingText('数据上传中...');
      setLoading(true);
      importEmployeeSecurity({...securityInfo, file: info.file, isUpdate: 0}).then(res => {
        if (res.flag) {
          notification.success({
            message: '导入成功',
            description: <>{res.data.map((item, index) => <div key={index}>{item}</div>)}</>,
          });
          setRenderFlag(!renderFlag);
        } else {

          notification.error({
            message: '导入失败',
            description: `${res.error} 。`,
          });
        }
        setLoading(false);
      })
    }
  };

  const filePropsUpdate = {
    name: 'file',
    multiple: false,
    showUploadList: false,
    customRequest: (info)=> {
      setLoadingText('数据上传中...');
      setLoading(true);
      importEmployeeSecurity({...securityInfo, file: info.file, isUpdate: 1}).then(res => {
        if (res.flag) {
          notification.success({
            message: '导入成功',
            description: <>{res.data.map((item, index) => <div key={index}>{item}</div>)}</>,
          });
          setRenderFlag(!renderFlag);
        } else {

          notification.error({
            message: '导入失败',
            description: `${res.error} 。`,
          });
        }
        setLoading(false);
      })
    }
  };

  const tableToolRender = () => ([
    <Button icon={<DownloadOutlined/>} onClick={downloadTemplate}>模板下载</Button>,
    <Button icon={<DownloadOutlined/>} onClick={downloadData}>批量导出</Button>,
    <Upload {...fileProps}><Button icon={<UploadOutlined/>}>批量导入(新增不更新)</Button></Upload>,
    <Upload {...filePropsUpdate}><Button icon={<UploadOutlined/>}>批量导入(新增且更新)</Button></Upload>,
  ])

  const downloadTemplate = () => {
    window.open(socialSecurityTemplateURL)
  };

  const downloadData = () => {
    let url = `/hr-ssc/api/api-admin/export/ExportSecurityEmployeeList?securityId=${current.securityId}`;
    window.open(url);
  };

  const onFormCancel = () => {
    // form.resetFields();
    setLoading(false);
    setAddUserList([]);
    setSecurityUserItems([]);
    onCancel()
  };

  const confirmSelectedUsers = (values) => {
    setAddUserList(values);
    setUserModalVisible(false);
  };

  const renderContent = () => {
    return (
      <>
        <Spin delay={300} spinning={loading} tip={loadingText} size='large'>
          <Row gutter={24}>
            <Col span={24}>
              <FormItem name="securityUsers">
                <EditDegradeTable tableToolbarRender={tableToolRender} addUserList={addUserList}
                                  securityUserItems={securityUserItems} securityInfo={securityInfo}/>
              </FormItem>
            </Col>
            <Col span={24}>
              <Button style={{width: '100%', marginBottom: 8}} type="dashed" onClick={() => setUserModalVisible(true)}>
                <PlusOutlined/>
                新增成员
              </Button>
            </Col>
          </Row>
        </Spin>
      </>
    )
  };

  const renderFooter = () => {
    return (
      <>
        <Button loading={loading} type="primary" onClick={() => onFormCancel()}>关闭</Button>
      </>
    )
  };

  return (
    <Modal
      title='方案人员配置'
      width={'90%'}
      destroyOnClose
      visible={visible}
      footer={renderFooter()}
      onOk={onFormCancel}
      onCancel={() => onFormCancel()}
      maskClosable={false}
      closable={false}
      okText="确认"
      cancelText="取消"
    >
      <Form {...formLayout} form={form}>
        {renderContent()}
      </Form>

      <SelectUserModal
        isDismiss={true}
        selectType={1}
        visible={userModalVisible}
        handleOk={confirmSelectedUsers}
        handleCancel={() => setUserModalVisible(false)}
      />
    </Modal>
  )
};


export default connect(({}) => ({}))(CreateForm)
